package com.hw.one.collect.modbus.util;



import com.hw.one.collect.modbus.entity.HeavyMetalMap;
import com.hw.one.collect.modbus.entity.ModbusData;
import com.hw.one.collect.util.ByteUtil;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.net.TCPMasterConnection;

public class ModbusTcpUtil {

    /**
     * @param ip
     * @param port
     * @param ref
     * @param slaveId
     * @return
     * @function: readonly register collect F04
     * @author: guoshenzhen
     */
    public static String readInputRegister(String ip, int port, int slaveId, int ref, int count) {
        TCPMasterConnection con = null;
        try {
            con = ModbusConnection.openTcpConnection(ip, port);
            con.connect();
            ReadInputRegistersRequest req = new ReadInputRegistersRequest(ref, count);
            req.setUnitID(slaveId);
            ModbusTCPTransaction trans = new ModbusTCPTransaction(con);

            trans.setRequest(req);
            trans.execute();
            String hexReq = req.getHexMessage();
            System.out.println("hexReq = " + hexReq);
            ReadInputRegistersResponse res = (ReadInputRegistersResponse) trans.getResponse();
            return res.getHexMessage();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null != con){
                con.close();
            }
        }
        return null;
    }

    public static final long getValue(int a, int b){
        long value = (a << 16) | b;
        return value;
    }

    public static final double getMetaValue(int a, int b){
        double d = getValue(a, b) / 100.0;
        return d;
    }


}